home *** CD-ROM | disk | FTP | other *** search
/ Programming an RTS Game with Direct3D / Programming an RTS Game with Direct3D.iso / Examples / Chapter 12 / Example 12.5 / terrain.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2006-07-16  |  25.5 KB  |  938 lines

  1. #include "terrain.h"
  2. #include "camera.h"
  3.  
  4. const DWORD TERRAINVertex::FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX2;
  5.  
  6. //////////////////////////////////////////////////////////////////////////////////////////
  7. //                                    PATCH                                                //
  8. //////////////////////////////////////////////////////////////////////////////////////////
  9.  
  10. PATCH::PATCH()
  11. {
  12.     m_pDevice = NULL;
  13.     m_pMesh = NULL;
  14. }
  15. PATCH::~PATCH()
  16. {
  17.     Release();
  18. }
  19.  
  20. void PATCH::Release()
  21. {
  22.     if(m_pMesh != NULL)
  23.         m_pMesh->Release();
  24.     m_pMesh = NULL;
  25. }
  26.  
  27. HRESULT PATCH::CreateMesh(TERRAIN &ter, RECT source, IDirect3DDevice9* Dev)
  28. {
  29.     if(m_pMesh != NULL)
  30.     {
  31.         m_pMesh->Release();
  32.         m_pMesh = NULL;
  33.     }
  34.  
  35.     try
  36.     {
  37.         m_pDevice = Dev;
  38.         m_mapRect = source;
  39.  
  40.         int width = source.right - source.left;
  41.         int height = source.bottom - source.top;
  42.         int nrVert = (width + 1) * (height + 1);
  43.         int nrTri = width * height * 2;
  44.  
  45.         if(FAILED(D3DXCreateMeshFVF(nrTri, nrVert, D3DXMESH_MANAGED, TERRAINVertex::FVF, m_pDevice, &m_pMesh)))
  46.         {
  47.             debug.Print("Couldn't create m_pMesh for PATCH");
  48.             return E_FAIL;
  49.         }
  50.  
  51.         m_BBox.max = D3DXVECTOR3(-10000.0f, -10000.0f, -10000.0f);
  52.         m_BBox.min = D3DXVECTOR3(10000.0f, 10000.0f, 10000.0f);
  53.  
  54.         //Create vertices
  55.         TERRAINVertex* ver = 0;
  56.         m_pMesh->LockVertexBuffer(0,(void**)&ver);
  57.         for(int z=source.top, z0 = 0;z<=source.bottom;z++, z0++)
  58.             for(int x=source.left, x0 = 0;x<=source.right;x++, x0++)
  59.             {
  60.                 MAPTILE *tile = ter.GetTile(x, z);
  61.  
  62.                 D3DXVECTOR3 pos = D3DXVECTOR3(x, tile->m_height, -z);
  63.                 D3DXVECTOR2 alphaUV = D3DXVECTOR2(x / (float)ter.m_size.x, z / (float)ter.m_size.y);        //Alpha UV
  64.                 D3DXVECTOR2 colorUV = alphaUV * 8.0f;                                                    //Color UV
  65.  
  66.                 ver[z0 * (width + 1) + x0] = TERRAINVertex(pos, ter.GetNormal(x, z), alphaUV, colorUV);
  67.  
  68.                 //Calculate bounding box bounds...
  69.                 if(pos.x < m_BBox.min.x)m_BBox.min.x = pos.x;
  70.                 if(pos.x > m_BBox.max.x)m_BBox.max.x = pos.x;
  71.                 if(pos.y < m_BBox.min.y)m_BBox.min.y = pos.y;
  72.                 if(pos.y > m_BBox.max.y)m_BBox.max.y = pos.y;
  73.                 if(pos.z < m_BBox.min.z)m_BBox.min.z = pos.z;
  74.                 if(pos.z > m_BBox.max.z)m_BBox.max.z = pos.z;
  75.             }
  76.         m_pMesh->UnlockVertexBuffer();
  77.  
  78.         //Calculate Indices
  79.         WORD* ind = 0;
  80.         m_pMesh->LockIndexBuffer(0,(void**)&ind);    
  81.         int index = 0;
  82.  
  83.         for(int z=source.top, z0 = 0;z<source.bottom;z++, z0++)
  84.             for(int x=source.left, x0 = 0;x<source.right;x++, x0++)
  85.             {
  86.                 //Triangle 1
  87.                 ind[index++] =   z0   * (width + 1) + x0;
  88.                 ind[index++] =   z0   * (width + 1) + x0 + 1;
  89.                 ind[index++] = (z0+1) * (width + 1) + x0;        
  90.  
  91.                 //Triangle 2
  92.                 ind[index++] = (z0+1) * (width + 1) + x0;
  93.                 ind[index++] =   z0   * (width + 1) + x0 + 1;
  94.                 ind[index++] = (z0+1) * (width + 1) + x0 + 1;
  95.             }
  96.  
  97.         m_pMesh->UnlockIndexBuffer();
  98.  
  99.         //Set Attributes
  100.         DWORD *att = 0, a = 0;
  101.         m_pMesh->LockAttributeBuffer(0,&att);
  102.         memset(att, 0, sizeof(DWORD)*nrTri);
  103.         m_pMesh->UnlockAttributeBuffer();
  104.     }
  105.     catch(...)
  106.     {
  107.         debug.Print("Error in PATCH::CreateMesh()");
  108.         return E_FAIL;
  109.     }
  110.  
  111.     return S_OK;
  112. }
  113.  
  114. void PATCH::Render()
  115. {
  116.     //Draw mesh
  117.     if(m_pMesh != NULL)
  118.         m_pMesh->DrawSubset(0);
  119. }
  120.  
  121. //////////////////////////////////////////////////////////////////////////////////////////
  122. //                                    TERRAIN                                                //
  123. //////////////////////////////////////////////////////////////////////////////////////////
  124.  
  125. TERRAIN::TERRAIN()
  126. {
  127.     m_pDevice = NULL;
  128.     m_pMapTiles = NULL;
  129. }
  130.  
  131. void TERRAIN::Init(IDirect3DDevice9* Dev, INTPOINT _size)
  132. {
  133.     m_pDevice = Dev;
  134.     m_size = _size;
  135.     m_pHeightMap = NULL;
  136.  
  137.     if(m_pMapTiles != NULL)    //Clear old m_pMapTiles
  138.         delete [] m_pMapTiles;
  139.  
  140.     //Create maptiles
  141.     m_pMapTiles = new MAPTILE[m_size.x * m_size.y];
  142.     memset(m_pMapTiles, 0, sizeof(MAPTILE)*m_size.x*m_size.y);
  143.  
  144.     //Clear old textures
  145.     for(int i=0;i<m_diffuseMaps.size();i++)
  146.         m_diffuseMaps[i]->Release();
  147.     m_diffuseMaps.clear();
  148.  
  149.     //Load textures
  150.     IDirect3DTexture9* grass = NULL, *mount = NULL, *snow = NULL;
  151.     if(FAILED(D3DXCreateTextureFromFile(Dev, "textures/grass.jpg", &grass)))debug.Print("Could not load grass.jpg");
  152.     if(FAILED(D3DXCreateTextureFromFile(Dev, "textures/mountain.jpg", &mount)))debug.Print("Could not load mountain.jpg");
  153.     if(FAILED(D3DXCreateTextureFromFile(Dev, "textures/snow.jpg", &snow)))debug.Print("Could not load snow.jpg");
  154.     m_diffuseMaps.push_back(grass);
  155.     m_diffuseMaps.push_back(mount);
  156.     m_diffuseMaps.push_back(snow);
  157.     m_pAlphaMap = NULL;
  158.     m_pLightMap = NULL;
  159.  
  160.     // Init font
  161.     D3DXCreateFont(m_pDevice, 40, 0, 0, 1, false,  
  162.                    DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,
  163.                    DEFAULT_PITCH | FF_DONTCARE, "Arial Black", &m_pProgressFont);
  164.  
  165.     //Load pixel & vertex shaders
  166.     m_dirToSun = D3DXVECTOR3(1.0f, 0.6f, 0.5f);
  167.     D3DXVec3Normalize(&m_dirToSun, &m_dirToSun);
  168.  
  169.     m_terrainPS.Init(Dev, "shaders/terrain.ps", PIXEL_SHADER);
  170.     m_terrainVS.Init(Dev, "shaders/terrain.vs", VERTEX_SHADER);
  171.     m_vsMatW = m_terrainVS.GetConstant("matW");
  172.     m_vsMatVP = m_terrainVS.GetConstant("matVP");
  173.     m_vsDirToSun = m_terrainVS.GetConstant("DirToSun");
  174.  
  175.     m_objectsPS.Init(Dev, "shaders/objects.ps", PIXEL_SHADER);
  176.     m_objectsVS.Init(Dev, "shaders/objects.vs", VERTEX_SHADER);
  177.     m_objMatW = m_objectsVS.GetConstant("matW");
  178.     m_objMatVP = m_objectsVS.GetConstant("matVP");
  179.     m_objDirToSun = m_objectsVS.GetConstant("DirToSun");
  180.     m_objMapSize = m_objectsVS.GetConstant("mapSize");
  181.  
  182.     //Create white material    
  183.     m_mtrl.Ambient = m_mtrl.Specular = m_mtrl.Diffuse  = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f);
  184.     m_mtrl.Emissive = D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f);
  185.  
  186.     GenerateRandomTerrain(9);
  187. }
  188.  
  189. void TERRAIN::Release()
  190. {
  191.     for(int i=0;i<m_patches.size();i++)
  192.         if(m_patches[i] != NULL)
  193.             m_patches[i]->Release();
  194.  
  195.     m_patches.clear();
  196.  
  197.     if(m_pHeightMap != NULL)
  198.     {
  199.         m_pHeightMap->Release();
  200.         delete m_pHeightMap;
  201.         m_pHeightMap = NULL;
  202.     }
  203.  
  204.     m_objects.clear();
  205. }
  206.  
  207. void TERRAIN::GenerateRandomTerrain(int numPatches)
  208. {
  209.     try
  210.     {
  211.         Release();
  212.  
  213.         //Create two heightmaps and multiply them
  214.         m_pHeightMap = new HEIGHTMAP(m_size, 20.0f);
  215.         HEIGHTMAP hm2(m_size, 2.0f);
  216.  
  217.         m_pHeightMap->CreateRandomHeightMap(rand()%2000, 1.0f, 0.7f, 7);
  218.         hm2.CreateRandomHeightMap(rand()%2000, 2.5f, 0.8f, 3);
  219.  
  220.         hm2.Cap(hm2.m_maxHeight * 0.4f);
  221.  
  222.         *m_pHeightMap *= hm2;
  223.         hm2.Release();
  224.         
  225.         //Add objects
  226.         HEIGHTMAP hm3(m_size, 1.0f);
  227.         hm3.CreateRandomHeightMap(rand()%1000, 5.5f, 0.9f, 7);
  228.  
  229.         for(int y=0;y<m_size.y;y++)
  230.             for(int x=0;x<m_size.x;x++)
  231.             {
  232.                 if(m_pHeightMap->GetHeight(x, y) == 0.0f && hm3.GetHeight(x, y) > 0.7f && rand()%6 == 0)
  233.                     AddObject(0, INTPOINT(x, y));    //Tree
  234.                 else if(m_pHeightMap->GetHeight(x, y) >= 1.0f && hm3.GetHeight(x, y) > 0.9f && rand()%20 == 0)
  235.                     AddObject(1, INTPOINT(x, y));    //Stone
  236.             }
  237.  
  238.         hm3.Release();
  239.  
  240.         InitPathfinding();
  241.         CreatePatches(numPatches);
  242.         CalculateAlphaMaps();
  243.         CalculateLightMap();
  244.     }
  245.     catch(...)
  246.     {
  247.         debug.Print("Error in TERRAIN::GenerateRandomTerrain()");
  248.     }
  249. }
  250.  
  251. void TERRAIN::CreatePatches(int numPatches)
  252. {
  253.     try
  254.     {
  255.         //Clear any old patches
  256.         for(int i=0;i<m_patches.size();i++)
  257.             if(m_patches[i] != NULL)
  258.                 m_patches[i]->Release();
  259.         m_patches.clear();
  260.  
  261.         //Create new patches
  262.         for(int y=0;y<numPatches;y++)
  263.         {
  264.             Progress("Creating Terrain Mesh", y / (float)numPatches);
  265.  
  266.             for(int x=0;x<numPatches;x++)
  267.             {
  268.                 RECT r = {x * (m_size.x - 1) / (float)numPatches, 
  269.                         y * (m_size.y - 1) / (float)numPatches, 
  270.                         (x+1) * (m_size.x - 1) / (float)numPatches,
  271.                         (y+1) * (m_size.y - 1) / (float)numPatches};
  272.                         
  273.                 PATCH *p = new PATCH();
  274.                 p->CreateMesh(*this, r, m_pDevice);
  275.                 m_patches.push_back(p);
  276.             }
  277.         }
  278.     }
  279.     catch(...)
  280.     {
  281.         debug.Print("Error in TERRAIN::CreatePatches()");
  282.     }
  283. }
  284.  
  285. void TERRAIN::CalculateAlphaMaps()
  286. {
  287.     Progress("Creating Alpha Map", 0.0f);
  288.  
  289.     //Clear old alpha maps
  290.     if(m_pAlphaMap != NULL)
  291.         m_pAlphaMap->Release();
  292.  
  293.     //Create new alpha map
  294.     D3DXCreateTexture(m_pDevice, 128, 128, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_pAlphaMap);
  295.  
  296.     //Lock the texture
  297.     D3DLOCKED_RECT sRect;
  298.     m_pAlphaMap->LockRect(0, &sRect, NULL, NULL);
  299.     BYTE *bytes = (BYTE*)sRect.pBits;
  300.     memset(bytes, 0, 128*sRect.Pitch);        //Clear texture to black
  301.  
  302.     for(int i=0;i<m_diffuseMaps.size();i++)
  303.         for(int y=0;y<sRect.Pitch / 4;y++)
  304.             for(int x=0;x<sRect.Pitch / 4;x++)
  305.             {
  306.                 int terrain_x = m_size.x * (x / (float)(sRect.Pitch / 4.0f));
  307.                 int terrain_y = m_size.y * (y / (float)(sRect.Pitch / 4.0f));
  308.                 MAPTILE *tile = GetTile(terrain_x, terrain_y);
  309.  
  310.                 if(tile != NULL && tile->m_type == i)
  311.                     bytes[y * sRect.Pitch + x * 4 + i] = 255;
  312.             }
  313.  
  314.     //Unlock the texture
  315.     m_pAlphaMap->UnlockRect(0);
  316.     
  317.     //D3DXSaveTextureToFile("alpha.bmp", D3DXIFF_BMP, m_pAlphaMap, NULL);
  318. }
  319.  
  320. void TERRAIN::CalculateLightMap()
  321. {
  322.     try
  323.     {
  324.         //Clear old alpha maps
  325.         if(m_pLightMap != NULL)
  326.             m_pLightMap->Release();
  327.  
  328.         //Create new light map
  329.         D3DXCreateTexture(m_pDevice, 256, 256, 1, D3DUSAGE_DYNAMIC, D3DFMT_L8, D3DPOOL_DEFAULT, &m_pLightMap);
  330.  
  331.         //Lock the texture
  332.         D3DLOCKED_RECT sRect;
  333.         m_pLightMap->LockRect(0, &sRect, NULL, NULL);
  334.         BYTE *bytes = (BYTE*)sRect.pBits;
  335.         memset(bytes, 255, 256*sRect.Pitch);        //Clear texture to white
  336.  
  337.         for(int y=0;y<sRect.Pitch;y++)
  338.         {
  339.             Progress("Calculating Lightmap", y / (float)sRect.Pitch);
  340.  
  341.             for(int x=0;x<sRect.Pitch;x++)
  342.             {
  343.                 float terrain_x = (float)m_size.x * (x / (float)(sRect.Pitch));
  344.                 float terrain_z = (float)m_size.y * (y / (float)(sRect.Pitch));
  345.  
  346.                 //Find patch that the terrain_x, terrain_z is over
  347.                 bool done = false;
  348.                 for(int p=0;p<m_patches.size() && !done;p++)
  349.                 {
  350.                     RECT mr = m_patches[p]->m_mapRect;
  351.  
  352.                     //Focus within patch maprect or not?
  353.                     if(terrain_x >= mr.left && terrain_x < mr.right &&
  354.                          terrain_z >= mr.top && terrain_z < mr.bottom)
  355.                     {            
  356.                         // Collect only the closest intersection
  357.                         RAY rayTop(D3DXVECTOR3(terrain_x, 10000.0f, -terrain_z), D3DXVECTOR3(0.0f, -1.0f, 0.0f));
  358.                         float dist = rayTop.Intersect(m_patches[p]->m_pMesh);
  359.  
  360.                         if(dist >= 0.0f)
  361.                         {
  362.                             RAY ray(D3DXVECTOR3(terrain_x, 10000.0f - dist + 0.01f, -terrain_z), m_dirToSun);
  363.  
  364.                             for(int p2=0;p2<m_patches.size() && !done;p2++)
  365.                                 if(ray.Intersect(m_patches[p2]->m_BBox) >= 0)
  366.                                 {
  367.                                     if(ray.Intersect(m_patches[p2]->m_pMesh) >= 0)    //In shadow
  368.                                     {
  369.                                         done = true;
  370.                                         bytes[y * sRect.Pitch + x] = 128;
  371.                                     }
  372.                                 }
  373.  
  374.                             done = true;
  375.                         }
  376.                     }
  377.                 }                        
  378.             }
  379.         }
  380.  
  381.         //Smooth lightmap        
  382.         for(int i=0;i<3;i++)
  383.         {
  384.             Progress("Smoothing the Lightmap", i / 3.0f);
  385.  
  386.             BYTE* tmpBytes = new BYTE[sRect.Pitch * sRect.Pitch];
  387.             memcpy(tmpBytes, sRect.pBits, sRect.Pitch * sRect.Pitch);
  388.  
  389.             for(int y=1;y<sRect.Pitch-1;y++)
  390.                 for(int x=1;x<sRect.Pitch-1;x++)
  391.                 {
  392.                     long index = y*sRect.Pitch + x;
  393.                     BYTE b1 = bytes[index];
  394.                     BYTE b2 = bytes[index - 1];
  395.                     BYTE b3 = bytes[index - sRect.Pitch];
  396.                     BYTE b4 = bytes[index + 1];
  397.                     BYTE b5 = bytes[index + sRect.Pitch];
  398.                     
  399.                     tmpBytes[index] = (BYTE)((b1 + b2 + b3 + b4 + b5) / 5);
  400.                 }
  401.  
  402.             memcpy(sRect.pBits, tmpBytes, sRect.Pitch * sRect.Pitch);
  403.             delete [] tmpBytes;
  404.         }
  405.  
  406.         //Unlock the texture
  407.         m_pLightMap->UnlockRect(0);
  408.         
  409.         //D3DXSaveTextureToFile("light.bmp", D3DXIFF_BMP, m_pLightMap, NULL);
  410.     }
  411.     catch(...)
  412.     {
  413.         debug.Print("Error in TERRAIN::CalculateLightMap()");
  414.     }
  415. }
  416.  
  417. D3DXVECTOR3 TERRAIN::GetNormal(int x, int y)
  418. {
  419.     //Neighboring map nodes (D, B, C, F, H, G)
  420.     INTPOINT mp[] = {INTPOINT(x-1, y),   INTPOINT(x, y-1), 
  421.                      INTPOINT(x+1, y-1), INTPOINT(x+1, y),
  422.                        INTPOINT(x, y+1),   INTPOINT(x-1, y+1)};
  423.  
  424.     //if there's an invalid map node return (0, 1, 0)
  425.     if(!Within(mp[0]) || !Within(mp[1]) || !Within(mp[2]) || 
  426.        !Within(mp[3]) || !Within(mp[4]) || !Within(mp[5]))
  427.         return D3DXVECTOR3(0.0f, 1.0f, 0.0f);
  428.  
  429.     //Calculate the normals of the 6 neighboring planes
  430.     D3DXVECTOR3 normal = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
  431.  
  432.     for(int i=0;i<6;i++)
  433.     {
  434.         D3DXPLANE plane;
  435.         D3DXPlaneFromPoints(&plane, 
  436.                             &GetWorldPos(INTPOINT(x, y)),
  437.                             &GetWorldPos(mp[i]), 
  438.                             &GetWorldPos(mp[(i + 1) % 6]));
  439.  
  440.         normal +=  D3DXVECTOR3(plane.a, plane.b, plane.c);
  441.     }
  442.  
  443.     D3DXVec3Normalize(&normal, &normal);
  444.     return normal;
  445. }
  446.  
  447. void TERRAIN::AddObject(int type, INTPOINT mappos)
  448. {
  449.     D3DXVECTOR3 pos = D3DXVECTOR3(mappos.x, m_pHeightMap->GetHeight(mappos), -mappos.y);    
  450.     D3DXVECTOR3 rot = D3DXVECTOR3((rand()%1000 / 1000.0f) * 0.13f, (rand()%1000 / 1000.0f) * 3.0f, (rand()%1000 / 1000.0f) * 0.13);
  451.  
  452.     float sca_xz = (rand()%1000 / 1000.0f) * 0.5f + 0.5f;
  453.     float sca_y = (rand()%1000 / 1000.0f) * 1.0f + 0.5f;
  454.     D3DXVECTOR3 sca = D3DXVECTOR3(sca_xz, sca_y, sca_xz);
  455.  
  456.     m_objects.push_back(OBJECT(type, mappos, pos, rot, sca));
  457. }
  458.  
  459. void TERRAIN::Render(CAMERA &camera, bool all)
  460. {
  461.     //Set render states        
  462.     m_pDevice->SetRenderState(D3DRS_LIGHTING, false);
  463.     m_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, true);    
  464.     
  465.     m_pDevice->SetTexture(0, m_pAlphaMap);
  466.     m_pDevice->SetTexture(1, m_diffuseMaps[0]);        //Grass
  467.     m_pDevice->SetTexture(2, m_diffuseMaps[1]);        //Mountain
  468.     m_pDevice->SetTexture(3, m_diffuseMaps[2]);        //Snow
  469.     m_pDevice->SetTexture(4, m_pLightMap);            //Lightmap
  470.     m_pDevice->SetMaterial(&m_mtrl);
  471.  
  472.     D3DXMATRIX world, vp;
  473.     
  474.     if(!all)
  475.         vp = camera.GetViewMatrix() * camera.GetProjectionMatrix();
  476.     else
  477.     {
  478.         D3DXMATRIX v, p;
  479.         m_pDevice->GetTransform(D3DTS_VIEW, &v);
  480.         m_pDevice->GetTransform(D3DTS_PROJECTION, &p);
  481.         vp = v * p;
  482.     }
  483.  
  484.     D3DXMatrixIdentity(&world);
  485.     m_pDevice->SetTransform(D3DTS_WORLD, &world);
  486.     
  487.     //Set vertex shader variables
  488.     m_terrainVS.SetMatrix(m_vsMatW, world);
  489.     m_terrainVS.SetMatrix(m_vsMatVP, vp);
  490.     m_terrainVS.SetVector3(m_vsDirToSun, m_dirToSun);
  491.  
  492.     m_terrainVS.Begin();
  493.     m_terrainPS.Begin();
  494.         
  495.     for(int p=0;p<m_patches.size();p++)
  496.         if(!camera.Cull(m_patches[p]->m_BBox) || all)
  497.             m_patches[p]->Render();
  498.  
  499.     m_terrainPS.End();
  500.     m_terrainVS.End();
  501.  
  502.     m_pDevice->SetTexture(1, NULL);
  503.     m_pDevice->SetTexture(2, NULL);
  504.     m_pDevice->SetTexture(3, NULL);
  505.     m_pDevice->SetTexture(4, NULL);
  506.  
  507.     //Render Objects
  508.     m_objectsVS.SetMatrix(m_objMatW, world);
  509.     m_objectsVS.SetMatrix(m_objMatVP, vp);
  510.     m_objectsVS.SetVector3(m_objDirToSun, m_dirToSun);
  511.     m_objectsVS.SetVector3(m_objMapSize, D3DXVECTOR3(m_size.x, m_size.y, 0.0f));
  512.  
  513.     m_pDevice->SetTexture(1, m_pLightMap);        //Lightmap
  514.     
  515.     m_objectsVS.Begin();
  516.     m_objectsPS.Begin();
  517.  
  518.     for(int i=0;i<m_objects.size();i++)
  519.         if(!camera.Cull(m_objects[i].m_BBox) || all)
  520.         {
  521.             D3DXMATRIX m = m_objects[i].m_meshInstance.GetWorldMatrix();
  522.             m_objectsVS.SetMatrix(m_objMatW, m);
  523.             m_objects[i].Render();
  524.         }
  525.  
  526.     m_objectsVS.End();
  527.     m_objectsPS.End();
  528. }
  529.  
  530. void TERRAIN::Progress(std::string text, float prc)
  531. {
  532.     m_pDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0L);
  533.     m_pDevice->BeginScene();
  534.     
  535.     RECT rc = {200, 250, 600, 300};
  536.     m_pProgressFont->DrawText(NULL, text.c_str(), -1, &rc, DT_CENTER | DT_VCENTER | DT_NOCLIP, 0xff000000);
  537.  
  538.     //Progress bar
  539.     D3DRECT r;
  540.     r.x1 = 200; r.x2 = 600;
  541.     r.y1 = 300; r.y2 = 340;
  542.     m_pDevice->Clear(1, &r, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff000000, 1.0f, 0L);
  543.     r.x1 = 202; r.x2 = 598;
  544.     r.y1 = 302; r.y2 = 338;
  545.     m_pDevice->Clear(1, &r, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0L);
  546.     r.x1 = 202; r.x2 = 202 + 396 * prc;
  547.     r.y1 = 302; r.y2 = 338;
  548.     m_pDevice->Clear(1, &r, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff00ff00, 1.0f, 0L);
  549.  
  550.     m_pDevice->EndScene();
  551.     m_pDevice->Present(0, 0, 0, 0);
  552. }
  553.  
  554. bool TERRAIN::Within(INTPOINT p)
  555. {
  556.     return p.x >= 0 && p.y >= 0 && p.x < m_size.x && p.y < m_size.y;
  557. }
  558.  
  559. void TERRAIN::InitPathfinding()
  560. {
  561.     try
  562.     {
  563.         //Read maptile heights & types from heightmap
  564.         for(int y=0;y<m_size.y;y++)
  565.             for(int x=0;x<m_size.x;x++)
  566.             {
  567.                 MAPTILE *tile = GetTile(x, y);
  568.                 if(m_pHeightMap != NULL)tile->m_height = m_pHeightMap->GetHeight(x, y);
  569.                 tile->m_mappos = INTPOINT(x, y);
  570.                 
  571.                 if(tile->m_height < 0.3f)         tile->m_type = 0;    //Grass
  572.                 else if(tile->m_height < 7.0f) tile->m_type = 1;    //Stone
  573.                 else                         tile->m_type = 2;    //Snow
  574.             }
  575.  
  576.         //Calculate tile cost as a function of the height variance
  577.         for(int y=0;y<m_size.y;y++)        
  578.             for(int x=0;x<m_size.x;x++)
  579.             {
  580.                 MAPTILE *tile = GetTile(x, y);
  581.  
  582.                 if(tile != NULL)
  583.                 {
  584.                     //Possible neighbors
  585.                     INTPOINT p[] = {INTPOINT(x-1, y-1), INTPOINT(x, y-1), INTPOINT(x+1, y-1),
  586.                                     INTPOINT(x-1, y),                      INTPOINT(x+1, y),
  587.                                     INTPOINT(x-1, y+1), INTPOINT(x, y+1), INTPOINT(x+1, y+1)};
  588.  
  589.                     float variance = 0.0f;
  590.                     int nr = 0;
  591.  
  592.                     //For each neighbor
  593.                     for(int i=0;i<8;i++)    
  594.                         if(Within(p[i]))
  595.                         {
  596.                             MAPTILE *neighbor = GetTile(p[i]);
  597.  
  598.                             if(neighbor != NULL)
  599.                             {
  600.                                 float v = neighbor->m_height - tile->m_height;
  601.                                 variance += (v * v);
  602.                                 nr++;
  603.                             }
  604.                         }
  605.  
  606.                     //Cost = height variance
  607.                     variance /= (float)nr;
  608.                     tile->m_cost = variance + 0.1f;
  609.                     if(tile->m_cost > 1.0f)tile->m_cost = 1.0f;
  610.  
  611.                     //If the tile cost is less than 1.0f, then we can walk on the tile
  612.                     tile->m_walkable = tile->m_cost < 0.5f;
  613.                 }
  614.             }
  615.  
  616.         //Make maptiles with objects on them not walkable
  617.         for(int i=0;i<m_objects.size();i++)
  618.         {
  619.             MAPTILE *tile = GetTile(m_objects[i].m_mappos);
  620.             if(tile != NULL)
  621.             {
  622.                 tile->m_walkable = false;
  623.                 tile->m_cost = 1.0f;
  624.             }
  625.         }
  626.  
  627.         //Connect m_pMapTiles using the neightbors[] pointers
  628.         for(int y=0;y<m_size.y;y++)        
  629.             for(int x=0;x<m_size.x;x++)
  630.             {
  631.                 MAPTILE *tile = GetTile(x, y);
  632.                 if(tile != NULL && tile->m_walkable)
  633.                 {
  634.                     //Clear old connections
  635.                     for(int i=0;i<8;i++)
  636.                         tile->m_pNeighbors[i] = NULL;
  637.  
  638.                     //Possible neighbors
  639.                     INTPOINT p[] = {INTPOINT(x-1, y-1), INTPOINT(x, y-1), INTPOINT(x+1, y-1),
  640.                                     INTPOINT(x-1, y),                      INTPOINT(x+1, y),
  641.                                     INTPOINT(x-1, y+1), INTPOINT(x, y+1), INTPOINT(x+1, y+1)};
  642.  
  643.                     //For each neighbor
  644.                     for(int i=0;i<8;i++)    
  645.                         if(Within(p[i]))
  646.                         {
  647.                             MAPTILE *neighbor = GetTile(p[i]);
  648.  
  649.                             //Connect tiles if the neighbor is walkable
  650.                             if(neighbor != NULL && neighbor->m_walkable)
  651.                                 tile->m_pNeighbors[i] = neighbor;
  652.                         }
  653.                 }
  654.             }
  655.  
  656.         CreateTileSets();
  657.     }
  658.     catch(...)
  659.     {
  660.         debug.Print("Error in InitPathfinding()");
  661.     }    
  662. }
  663.  
  664. void TERRAIN::CreateTileSets()
  665. {
  666.     try
  667.     {
  668.         int setNo = 0;
  669.         for(int y=0;y<m_size.y;y++)        //Set a unique set for each tile...
  670.             for(int x=0;x<m_size.x;x++)
  671.                 m_pMapTiles[x + y * m_size.x].m_set = setNo++;
  672.  
  673.         bool changed = true;
  674.         while(changed)
  675.         {
  676.             changed = false;
  677.  
  678.             for(int y=0;y<m_size.y;y++)
  679.                 for(int x=0;x<m_size.x;x++)
  680.                 {
  681.                     MAPTILE *tile = GetTile(x, y);
  682.  
  683.                     //Find the lowest set of a neighbor
  684.                     if(tile != NULL && tile->m_walkable)
  685.                     {
  686.                         for(int i=0;i<8;i++)
  687.                             if(tile->m_pNeighbors[i] != NULL &&
  688.                                 tile->m_pNeighbors[i]->m_walkable &&
  689.                                 tile->m_pNeighbors[i]->m_set < tile->m_set)
  690.                             {
  691.                                 changed = true;
  692.                                 tile->m_set = tile->m_pNeighbors[i]->m_set;
  693.                             }
  694.                     }
  695.                 }
  696.         }
  697.     }
  698.     catch(...)
  699.     {
  700.         debug.Print("Error in TERRAIN::CreateTileSets()");
  701.     }
  702. }
  703.  
  704. float H(INTPOINT a, INTPOINT b)
  705. {
  706.     //return abs(a.x - b.x) + abs(a.y - b.y);
  707.     return a.Distance(b);
  708. }
  709.  
  710. std::vector<INTPOINT> TERRAIN::GetPath(INTPOINT start, INTPOINT goal)
  711. {
  712.     try
  713.     {
  714.         //Check that the two points are within the bounds of the map
  715.         MAPTILE *startTile = GetTile(start);
  716.         MAPTILE *goalTile = GetTile(goal);
  717.  
  718.         if(!Within(start) || !Within(goal) || start == goal || startTile == NULL || goalTile == NULL)
  719.             return std::vector<INTPOINT>();
  720.  
  721.         //Check if a path exists
  722.         if(!startTile->m_walkable || !goalTile->m_walkable || startTile->m_set != goalTile->m_set)
  723.             return std::vector<INTPOINT>();
  724.  
  725.         //Init Search
  726.         long numTiles = m_size.x * m_size.y;
  727.         for(long l=0;l<numTiles;l++)
  728.         {
  729.             m_pMapTiles[l].f = m_pMapTiles[l].g = INT_MAX;        //Clear F,G
  730.             m_pMapTiles[l].open = m_pMapTiles[l].closed = false;    //Reset Open and Closed
  731.         }
  732.  
  733.         std::vector<MAPTILE*> open;                //Create Our Open list
  734.         startTile->g = 0;                        //Init our starting point (SP)
  735.         startTile->f = H(start, goal);
  736.         startTile->open = true;
  737.         open.push_back(startTile);                //Add SP to the Open list
  738.  
  739.         bool found = false;                    // Search as long as a path hasnt been found,
  740.         while(!found && !open.empty())        // or there is no more tiles to search
  741.         {                                                
  742.             MAPTILE * best = open[0];        // Find the best tile (i.e. the lowest F value)
  743.             int bestPlace = 0;
  744.             for(int i=1;i<open.size();i++)
  745.                 if(open[i]->f < best->f)
  746.                 {
  747.                     best = open[i];
  748.                     bestPlace = i;
  749.                 }
  750.             
  751.             if(best == NULL)break;            //No path found
  752.  
  753.             open[bestPlace]->open = false;
  754.             open.erase(&open[bestPlace]);    // Take the best node out of the Open list
  755.  
  756.             if(best->m_mappos == goal)        //If the goal has been found
  757.             {
  758.                 std::vector<INTPOINT> p, p2;
  759.                 MAPTILE *point = best;
  760.  
  761.                 while(point->m_mappos != start)    // Generate path
  762.                 {
  763.                     p.push_back(point->m_mappos);
  764.                     point = point->m_pParent;
  765.                 }
  766.  
  767.                 for(int i=p.size()-1;i!=0;i--)    // Reverse path
  768.                     p2.push_back(p[i]);
  769.                 p2.push_back(goal);
  770.                 return p2;
  771.             }
  772.             else
  773.             {
  774.                 for(i=0;i<8;i++)                    // otherwise, check the neighbors of the
  775.                     if(best->m_pNeighbors[i] != NULL)    // best tile
  776.                     {
  777.                         bool inList = false;        // Generate new G and F value
  778.                         float newG = best->g + 1.0f;
  779.                         float d = H(best->m_mappos, best->m_pNeighbors[i]->m_mappos);
  780.                         float newF = newG + H(best->m_pNeighbors[i]->m_mappos, goal) + best->m_pNeighbors[i]->m_cost * 5.0f * d;
  781.  
  782.                         if(best->m_pNeighbors[i]->open || best->m_pNeighbors[i]->closed)
  783.                         {
  784.                             if(newF < best->m_pNeighbors[i]->f)    // If the new F value is lower
  785.                             {
  786.                                 best->m_pNeighbors[i]->g = newG;    // update the values of this tile
  787.                                 best->m_pNeighbors[i]->f = newF;
  788.                                 best->m_pNeighbors[i]->m_pParent = best;                                
  789.                             }
  790.                             inList = true;
  791.                         }
  792.  
  793.                         if(!inList)            // If the neighbor tile isn't in the Open or Closed list
  794.                         {
  795.                             best->m_pNeighbors[i]->f = newF;        //Set the values
  796.                             best->m_pNeighbors[i]->g = newG;
  797.                             best->m_pNeighbors[i]->m_pParent = best;
  798.                             best->m_pNeighbors[i]->open = true;
  799.                             open.push_back(best->m_pNeighbors[i]);    //Add it to the open list    
  800.                         }
  801.                     }
  802.  
  803.                 best->closed = true;        //The best tile has now been searched, add it to the Closed list
  804.             }
  805.         }
  806.  
  807.         return std::vector<INTPOINT>();        //No path found, return an empty path
  808.         
  809.     }
  810.     catch(...)
  811.     {
  812.         debug.Print("Error in TERRAIN::GetPath()");
  813.         return std::vector<INTPOINT>();
  814.     }
  815. }
  816.  
  817. MAPTILE* TERRAIN::GetTile(int x, int y)
  818. {
  819.     if(m_pMapTiles == NULL)return NULL;
  820.  
  821.     try
  822.     {
  823.         return &m_pMapTiles[x + y * m_size.x];
  824.     }
  825.     catch(...)
  826.     {
  827.         return NULL;
  828.     }
  829. }
  830.  
  831. void TERRAIN::SaveTerrain(char fileName[])
  832. {
  833.     try
  834.     {
  835.         std::ofstream out(fileName, std::ios::binary);        //Binary format
  836.  
  837.         if(out.good())
  838.         {
  839.             out.write((char*)&m_size, sizeof(INTPOINT));    //Write map size
  840.  
  841.             //Write all the maptile information needed to recreate the map
  842.             for(int y=0;y<m_size.y;y++)
  843.                 for(int x=0;x<m_size.x;x++)
  844.                 {
  845.                     MAPTILE *tile = GetTile(x, y);
  846.                     out.write((char*)&tile->m_type, sizeof(int));            //type
  847.                     out.write((char*)&tile->m_height, sizeof(float));        //Height
  848.                 }
  849.  
  850.             //Write all the objects
  851.             int numObjects = m_objects.size();
  852.             out.write((char*)&numObjects, sizeof(int));     //Num Objects
  853.             for(int i=0;i<m_objects.size();i++)
  854.             {
  855.                 out.write((char*)&m_objects[i].m_type, sizeof(int));                //type
  856.                 out.write((char*)&m_objects[i].m_mappos, sizeof(INTPOINT));            //mappos
  857.                 out.write((char*)&m_objects[i].m_meshInstance.m_pos, sizeof(D3DXVECTOR3));    //Pos
  858.                 out.write((char*)&m_objects[i].m_meshInstance.m_rot, sizeof(D3DXVECTOR3));    //Rot
  859.                 out.write((char*)&m_objects[i].m_meshInstance.m_sca, sizeof(D3DXVECTOR3));    //Sca
  860.             }
  861.         }
  862.  
  863.         out.close();
  864.     }
  865.     catch(...)
  866.     {
  867.         debug.Print("Error in TERRAIN::SaveTerrain()");
  868.     }
  869. }
  870.  
  871. void TERRAIN::LoadTerrain(char fileName[])
  872. {
  873.     try
  874.     {
  875.         std::ifstream in(fileName, std::ios::binary);        //Binary format
  876.  
  877.         if(in.good())
  878.         {
  879.             Release();    //Release all terrain resources
  880.  
  881.             in.read((char*)&m_size, sizeof(INTPOINT));    //read map size
  882.         
  883.             if(m_pMapTiles != NULL)    //Clear old maptiles
  884.                 delete [] m_pMapTiles;
  885.  
  886.             //Create new maptiles
  887.             m_pMapTiles = new MAPTILE[m_size.x * m_size.y];
  888.             memset(m_pMapTiles, 0, sizeof(MAPTILE)*m_size.x*m_size.y);
  889.  
  890.  
  891.             //Read the maptile information
  892.             for(int y=0;y<m_size.y;y++)
  893.                 for(int x=0;x<m_size.x;x++)
  894.                 {
  895.                     MAPTILE *tile = GetTile(x, y);
  896.                     in.read((char*)&tile->m_type, sizeof(int));            //type
  897.                     in.read((char*)&tile->m_height, sizeof(float));        //Height
  898.                 }
  899.  
  900.             //Read number of objects
  901.             int numObjects = 0;
  902.             in.read((char*)&numObjects, sizeof(int));
  903.             for(int i=0;i<numObjects;i++)
  904.             {
  905.                 int type = 0;
  906.                 INTPOINT mp;
  907.                 D3DXVECTOR3 p, r, s;
  908.  
  909.                 in.read((char*)&type, sizeof(int));            //type
  910.                 in.read((char*)&mp, sizeof(INTPOINT));        //mappos
  911.                 in.read((char*)&p, sizeof(D3DXVECTOR3));    //Pos
  912.                 in.read((char*)&r, sizeof(D3DXVECTOR3));    //Rot
  913.                 in.read((char*)&s, sizeof(D3DXVECTOR3));    //Sca
  914.  
  915.                 m_objects.push_back(OBJECT(type, mp, p, r, s));
  916.             }
  917.  
  918.             //Recreate Terrain
  919.             InitPathfinding();
  920.             CreatePatches(3);
  921.             CalculateAlphaMaps();
  922.             CalculateLightMap();
  923.         }
  924.  
  925.         in.close();
  926.     }
  927.     catch(...)
  928.     {
  929.         debug.Print("Error in TERRAIN::LoadTerrain()");
  930.     }
  931. }
  932.  
  933. D3DXVECTOR3 TERRAIN::GetWorldPos(INTPOINT mappos)
  934. {
  935.     if(!Within(mappos))return D3DXVECTOR3(0, 0, 0);
  936.     MAPTILE *tile = GetTile(mappos);
  937.     return D3DXVECTOR3(mappos.x, tile->m_height, -mappos.y);
  938. }